import { Button, Checkbox, Input, message } from 'antd';
import { useRef } from 'react';

import { SvgIcon } from '@/components/icon';
import Modals from '@/components/modals/Modals';
import NotData from '@/components/NotData';
import FilePreviewer from '@/pages/components/fileviewer/FilePreviewer';
import { KnowledgeBaseApprovalStore } from '@/store/knowledgeBaseApproval';

import '../index.scss';

import DocumentMessage from './DocumentMessage';

interface ViewAllProps {
  allDownloadData?: any;
  allDownloadIndex?: number;
  isAllDownload?: boolean;
  originalData?: any;
  keys?: string;
  rejectValue?: string;
  url?: string;
  rowData?: any;
  fileName?: string;
  defaultValue?: string;
  loading?: boolean;
  isShow?: boolean;
  isAllClose?: () => void;
  setIsModalOpen?: (isModalOpen: boolean) => void;
  setRejectValue?: (rejectValue: string) => void;
  setDefaultTrigger?: (trigger: boolean) => void;
  setAllDownloadData?: (allDownloadData: any) => void;
  changeAllDownload?: (item: any) => void;

  handleModalCancel?: () => void;
  changeAllDownloadIndex?: (index: number, item: any) => void;
  handleModal?: (row: any, flag: string) => void;
  setLoading?: (loading: boolean) => void;
  setDefaultValue?: (defaultValue: string) => void;
  handlePass?: (row: any) => void;
  setRejectRow?: (rejectRow: any) => void;
  updateDownloadData?: (type: string, row: any) => void;
  setRowData?: (rowData: any) => void;
  setIsShow?: (isShow: boolean) => void;
  handleModalOk?: (row: any) => void;
}

export default function ViewAll({
  allDownloadData,
  allDownloadIndex,
  isAllDownload,
  originalData,
  keys,
  rowData,
  url,
  fileName,
  loading,
  defaultValue,
  isShow,
  rejectValue,
  isAllClose = () => {},
  setRejectValue = () => {},
  setIsModalOpen = () => {},
  setDefaultTrigger = () => {},
  setAllDownloadData = () => {},
  changeAllDownload = () => {},

  handleModalCancel = () => {},
  changeAllDownloadIndex = () => {},
  handleModal = () => {},
  setLoading = () => {},
  setDefaultValue = () => {},
  handlePass = () => {},
  setRejectRow = () => {},
  updateDownloadData = () => {},
  setRowData = () => {},
  setIsShow = () => {},
  handleModalOk = () => {},
}: ViewAllProps) {
  // const [isShow, setIsShow] = useState(false);
  const { setIsButtonShow, radioValue, checkoutList, showTitle } = KnowledgeBaseApprovalStore();
  const [messageApi, contextHolder] = message.useMessage();
  const searchTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  // 计算全选状态
  const checkAll = allDownloadData.length > 0 && allDownloadData.every((item: any) => item.checked);
  const checkDisabled =
    allDownloadData.length > 0 &&
    allDownloadData.every(
      (item: any) =>
        item.reviewStatus === 'upload_pass' ||
        item.reviewStatus === 'delete_pass' ||
        item.reviewStatus === 'upload_reject' ||
        item.reviewStatus === 'delete_reject',
    );
  const indeterminate =
    allDownloadData.some((item: any) => item.checked) &&
    !allDownloadData.every((item: any) => item.checked);

  // 全选/取消全选处理
  const handleCheckAllChange = (e: any) => {
    const newData = allDownloadData.map((item: any) => ({
      ...item,
      checked: e.target.checked,
    }));
    setAllDownloadData(newData);
    setIsShow(true);
  };

  // 单个项目选择处理
  const handleSingleCheckChange = (item: any, index: number) => {
    const newData = [...allDownloadData];
    newData[index] = {
      ...item,
      checked: !item.checked,
    };
    setAllDownloadData(newData);
    setIsShow(true);
  };
  // 触发通过和驳回
  const changeAllview = (type: string) => {
    // 过滤出已选中且状态不是pass或reject的项
    const selectedItems = allDownloadData.filter(
      (item: any) =>
        item.checked &&
        item.reviewStatus !== 'upload_pass' &&
        item.reviewStatus !== 'upload_reject' &&
        item.reviewStatus !== 'delete_pass' &&
        item.reviewStatus !== 'delete_reject',
    );
    // console.log(selectedItems);
    setRowData([]);
    if (selectedItems.length == 0) {
      messageApi.error('请勾选需要操作的项');
      return;
    }
    if (type === 'reject') {
      setIsButtonShow(true);
      setRejectRow(selectedItems);
      setDefaultTrigger(false);
      if (radioValue) {
        updateDownloadData(type, selectedItems); // 调用驳回
        handleModalOk(selectedItems); // 直接走驳回
      } else {
        setIsModalOpen(true);
      }
    } else {
      updateDownloadData(type, selectedItems);
      handlePass(selectedItems);
      setIsShow(false);
    }
  };

  return (
    <div>
      {contextHolder}
      <Modals
        title={<div>搜索文档名/关键字</div>}
        width={1200}
        centered
        open={isAllDownload}
        onCancel={handleModalCancel}
        footerCancelHidden
        footerOkHidden
        modelContentClassName="!m-0  !p-6"
        line={false}
        zIndex={10}
        isDisplay
      >
        <div className="hide-scrollbar  flex h-full justify-between">
          <div className=" w-[30%] flex-shrink-0 rounded-xl  bg-bg-3  p-4">
            <div>
              <Input
                className="mb-[10px] h-[32px] rounded-md"
                placeholder="搜索文档名/关键字"
                suffix={<SvgIcon icon="work-ic6" size={16} />}
                value={defaultValue}
                onChange={(e) => {
                  const searchValue = e.target.value.trim();
                  setDefaultValue(searchValue);
                  if (searchTimerRef.current) clearTimeout(searchTimerRef.current);
                  searchTimerRef.current = setTimeout(() => {
                    if (searchValue === '') {
                      setAllDownloadData(originalData);
                    } else {
                      const filteredData = originalData.filter(
                        (item: any) =>
                          item.fileName.toLowerCase().includes(searchValue.toLowerCase()) ||
                          (item.keyword &&
                            item.keyword.toLowerCase().includes(searchValue.toLowerCase())),
                      );
                      setAllDownloadData(filteredData);
                    }
                  }, 500);
                }}
              />
              {keys === '1' && (
                <div className="flex  h-7 items-center justify-between pl-4">
                  <Checkbox
                    indeterminate={indeterminate}
                    onChange={handleCheckAllChange}
                    checked={checkAll}
                    disabled={checkDisabled}
                  >
                    <div className="ml-3">全选</div>
                  </Checkbox>
                  {allDownloadData.some((item: any) => item.checked) &&
                    isShow && ( // 通过驳回完需要隐藏吗
                      <div className="flex items-center justify-center gap-3 ">
                        <Button
                          danger
                          className="!h-auto  !w-auto  !rounded-md border border-[#FFBFB9] !bg-functional-red !px-4 !py-2 !text-sm !leading-none !text-error"
                          onClick={() => changeAllview('reject')}
                        >
                          批量驳回
                        </Button>
                        <Button
                          type="primary"
                          shape="round"
                          className="!h-auto !w-auto !rounded-md !px-4 !py-2 !text-sm !leading-none"
                          onClick={() => changeAllview('pass')}
                        >
                          批量通过
                        </Button>
                      </div>
                    )}
                </div>
              )}
            </div>
            {allDownloadData.length > 0 ? (
              <div
                className={` hide-scrollbar mr-4 mt-3 ${
                  keys === '1' ? 'h-[540px]' : 'h-[568px]'
                }  w-full overflow-auto`}
              >
                {allDownloadData.map((item: any, index: number) => (
                  <div
                    onClick={() => changeAllDownloadIndex(index, item)}
                    className={`mb-5 flex h-[76px] cursor-pointer rounded-md p-4

                    ${
                      allDownloadIndex === index ? 'border border-[#8EC5FD] bg-white' : 'bg-fill-2'
                    } `}
                    key={`${item.fileName}-${index}`}
                  >
                    <div>
                      {keys === '1' && (
                        <Checkbox
                          className="!mr-4"
                          checked={item.checked || false}
                          onChange={(e) => {
                            e.stopPropagation();
                            e.preventDefault();
                            handleSingleCheckChange(item, index);
                          }}
                          disabled={
                            item.reviewStatus === 'upload_pass' ||
                            item.reviewStatus === 'delete_pass' ||
                            item.reviewStatus === 'upload_reject' ||
                            item.reviewStatus === 'delete_reject'
                          }
                        />
                      )}
                    </div>
                    <div className="min-w-0 flex-1">
                      <div className="truncate text-sm text-text-5" title={item.fileName}>
                        {item.fileName}
                      </div>
                      <div
                        className={`${
                          allDownloadIndex === index ? 'all-download-item1' : ''
                        } relative   mt-1 flex  items-center justify-between  text-sm  text-[#474C5F]`}
                      >
                        <div
                          style={{ borderRadius: '20px 0 20px 0px' }}
                          className={`  text-center text-xs
                        ${keys === '1' ? '' : ''}
                        `}
                        >
                          {item.reviewStatus === 'upload_pass' ||
                          item.reviewStatus === 'upload_reject' ||
                          item.reviewStatus === 'upload_publish' ? (
                            <div className="rounded bg-@brand-color-light px-2 py-1 text-primary">
                              新增
                            </div>
                          ) : (
                            <div className="rounded bg-@error-color-light px-2 py-1 text-error">
                              删除
                            </div>
                          )}
                        </div>

                        <div
                          className={`
                          ml-2
                            ${
                              item.reviewStatus === 'upload_reject' ||
                              item.reviewStatus === 'delete_reject' ||
                              item.reviewStatus === 'delete_reject_review' ||
                              item.reviewStatus === 'delete_reject_ignore' ||
                              item.reviewStatus === 'upload_reject_review' ||
                              item.reviewStatus === 'upload_reject_delete'
                                ? ' text-error '
                                : item.reviewStatus === 'upload_pass' ||
                                  item.reviewStatus === 'delete_pass'
                                ? ' text-@success-color'
                                : ' text-text-2'
                            }
                          `}
                        >
                          {item.reviewStatus === 'upload_reject' ||
                          item.reviewStatus === 'delete_reject' ||
                          item.reviewStatus === 'delete_reject_review' ||
                          item.reviewStatus === 'delete_reject_ignore' ||
                          item.reviewStatus === 'upload_reject_review' ||
                          item.reviewStatus === 'upload_reject_delete'
                            ? '驳回'
                            : item.reviewStatus === 'upload_pass' ||
                              item.reviewStatus === 'delete_pass'
                            ? '通过'
                            : '未审批'}
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="flex h-full items-center">
                <NotData iconSize={80} textClassName="text-sm" />
              </div>
            )}
          </div>
          <div className="mx-4 w-px self-stretch bg-line-1" />
          <div className="flex min-h-0 flex-1 flex-col">
            {checkoutList.length > 0 && <DocumentMessage />}
            {showTitle ? null : (
              <>
                {allDownloadIndex == -1 ? (
                  <div className="h-full w-full rounded-xl bg-bg-3  text-center">
                    <NotData iconSize={80} textClassName="text-sm" fontText="无预览信息" />
                  </div>
                ) : (
                  <div className="flex min-h-0 w-full flex-1 flex-col">
                    {(rowData?.reviewStatus === 'upload_reject' ||
                      rowData?.reviewStatus === 'delete_reject' ||
                      rowData?.reviewStatus === 'upload_reject_review' ||
                      rowData?.reviewStatus === 'delete_reject_review') &&
                      keys === '2' && (
                        <div className="mb-5 h-[130px] rounded-xl bg-bg-3 text-center">
                          {rowData.reason}
                        </div>
                      )}
                    <div className="flex min-h-0 flex-1 flex-col rounded-xl text-center">
                      <div className="flex-1 overflow-auto rounded-xl">
                        {url ? (
                          <div
                            className={`
                              ${
                                keys === '1'
                                  ? checkoutList.length > 0
                                    ? 'h-[560px]'
                                    : 'h-[608px]'
                                  : rowData.reviewStatus === 'upload_reject' ||
                                    rowData.reviewStatus === 'delete_reject' ||
                                    rowData.reviewStatus === 'upload_reject_review' ||
                                    rowData.reviewStatus === 'delete_reject_review'
                                  ? checkoutList.length > 0
                                    ? 'h-[456px]'
                                    : 'h-[504px]'
                                  : checkoutList.length > 0
                                  ? 'h-[606px]'
                                  : 'h-[654px]'
                              }
                            `}
                          >
                            {/* ? 'h-[calc(56vh-90px)]'
                               : 'h-[calc(56vh-50px)]' */}
                            <FilePreviewer
                              previewUrl={url}
                              fileName={fileName}
                              loading={!!loading}
                              setLoading={setLoading}
                            />
                          </div>
                        ) : (
                          <div className="h-full bg-bg-3 p-2 text-left">{fileName}</div>
                        )}
                      </div>
                      {keys === '1' && (
                        <div className="flex items-center justify-end gap-3 pt-3">
                          <Button
                            danger
                            className="!h-auto !w-auto !rounded-md !bg-functional-red !px-6 !py-2 !text-sm !leading-none !text-error"
                            onClick={() => handleModal(rowData, 'reject')}
                          >
                            驳回
                          </Button>
                          <Button
                            type="primary"
                            shape="round"
                            className={`!h-auto !w-auto !rounded-md !px-6 !py-2 !text-sm !leading-none `}
                            onClick={() => handleModal(rowData, 'pass')}
                          >
                            通过
                          </Button>
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </>
            )}
          </div>
        </div>
      </Modals>
    </div>
  );
}
